<template>
  <div class="page">
    <div class="content">
      <div class="top"></div>
      <div class="cont">
        <div class="from-cont">
          <form
            v-if="!info.order_id"
            id="dt-success-cont"
            action=""
            novalidate
            role="form"
          >
            <div class="dt-desc">
              <div class="dt-desc-left">
                <span class="iconfont dt-icon icon-icon_service"></span>
              </div>
              <div class="dt-desc-right">
                <p class="dt-desc-title">支付结果</p>
                <p class="dt-desc-sm">系统正在处理</p>
              </div>
            </div>
            <div class="dt-suc-title shadow-lg">
              <div class="dt-suc_cont">
                <div class="dt-form shadow-lg">
                  <div class="dt-form-row2">
                    <div class="dt-form-row-rmb">
                      您好，请稍后，订单正在处理...
                    </div>
                    <div class="dt-form-row-money"></div>
                  </div>
                </div>
              </div>
            </div>
          </form>
          <form
            v-else
            id="dt-/static/depesit/-cont"
            action=""
            novalidate
            role="form"
          >
            <div class="dt-desc">
              <div class="dt-desc-left">
                <span
                  v-if="!is_payment"
                  class="iconfont dt-icon icon-icon_safety"
                />

                <span
                  v-else
                  class="iconfont dt-icon"
                  :class="{
                    'icon-icon_roundclose': info.status != 1,
                    'icon-icon_safety': info.status == 1,
                  }"
                />
              </div>
              <div class="dt-desc-right">
                <p class="dt-desc-title" v-if="!is_payment">
                  {{ form_type == 2 ? "拼团成功" : "预约成功" }}
                </p>
                <p class="dt-desc-title" v-else>
                  <template v-if="form_type == 2">
                    {{ info.status == 1 ? "拼团成功" : "支付失败" }}
                  </template>
                  <template v-else>
                    {{ info.status == 1 ? "预约成功" : "支付失败" }}
                  </template>
                </p>

                <p class="dt-desc-sm">
                  {{ info.status == 1 ? "感谢您的购买" : "感谢您的支持" }}
                </p>
              </div>
            </div>
            <div class="dt-suc-title shadow-lg">
              <div class="dt-suc_cont">
                <div class="dt-form shadow-lg">
                  <div class="dt-form-row2" v-if="is_payment">
                    <div class="dt-form-row-rmb">￥</div>
                    <div class="dt-form-row-money">
                      {{ info.dep_amount | toFixed }}
                    </div>
                  </div>
                  <div
                    class="dt-form-row"
                    v-if="(info.status == 1 || !is_payment) && customer.user_id"
                  >
                    <div class="dt-form-row-cont" style="text-align: center">
                      <long-touch-wechat
                        :image="[4, 5].includes(customer.contact_type)"
                        :qrcode="qrcode"
                        @callback="adBehavior('copy')"
                      />
                    </div>
                    <div class="dt-form-row-title" style="color: red; font-size: 16px; text-align: center">
                      专属客服微信 (长按添加好友)
                    </div>
                  </div>
                  <template v-if="is_payment">
                    <div class="dt-form-feng"></div>
                    <div class="dt-form-row">
                      <div class="dt-form-row-title">订单号</div>
                      <div class="dt-form-row-cont dt-order-id">
                        {{ info.order_id }}
                      </div>
                    </div>
                    <div class="dt-form-row" v-if="info.status == 1">
                      <div class="dt-form-row-title">支付日期</div>
                      <div class="dt-form-row-cont dt-order-pay-date">
                        {{ info.pay_date }}
                      </div>
                    </div>
                    <div class="dt-form-row">
                      <div class="dt-form-row-title">支付方式</div>
                      <div class="dt-form-row-cont dt-order-pay-type">
                        {{ info.pay_type }}
                      </div>
                    </div>
                    <div class="dt-form-row">
                      <div class="dt-form-row-title">支付状态</div>
                      <div class="dt-form-row-cont dt-order-pay-stauts">
                        {{
                          info.status == 1 ? "已支付" : "订单未支付或在处理中"
                        }}
                      </div>
                    </div>
                    <!-- <div class="dt-form-row">
										<div class="dt-form-row-title">专属客服</div>
										<div class="dt-form-row-cont dt-order-user"></div>
									</div> -->
                  </template>
                </div>
                <div class="dt-copy" v-if="info.status == 1">
                  请截图发给您的专属客服
                </div>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { isWechat } from "@/utils/validate";
import qs from "qs";
import LongTouchWechat from "@/components/long-touch-wechat";
import tpl from "@/mixins/tpl";
import includeJs from "@/utils/include-js";
import { on, off } from "@/utils/dom";
export default {
  mixins: [tpl],
  components: {
    LongTouchWechat,
  },
  metaInfo: {
    title: "下定结果",
  },
  data() {
    return {
      info: {},
      is_payment: true,
      form_type: 0,
    };
  },
  computed: {
    qrcode() {
      const { contact_type, image_url, wxk_image_url, contact } = this.customer;
      if (contact_type == 4) {
        return image_url;
      }
      if (contact_type == 5) {
        return wxk_image_url;
      }
      return contact;
    },
  },
  created() {
    this.init();
    on(document, "visibilitychange", this.visibilitychange);
    // 记得销毁一些全局的的事件
    this.$once("hook:beforeDestroy", () => {
      off(document, "visibilitychange", this.visibilitychange);
    });
  },
  methods: {
    async init() {
      await this.$getUni();
      const uniEnv = this.$uni.env || {};
      const { query } = this.$route;
      let is_payment = query.is_payment != 0;
      let { merOrderId } = query;
      let resData = "";
      if (merOrderId) {
        resData = await this.$api
          .getadparam({ order_id: merOrderId.substring(4) })
          .catch(() => ({}));
      }
      let adReturn = qs.parse(resData);
      let paySuccess = query.status == "TRADE_SUCCESS";
      let needForm = query.form_pay == 2 && paySuccess;
      let url = `${
        needForm ? `${adReturn.page || "ads"}/form` : "pay/success"
      }?${qs.stringify(query)}`;

      let allUrl = `${location.origin}/${url}${resData ? "&" : ""}${
        resData ?? ""
      }`;

      if (!needForm && adReturn.pay_result_land && paySuccess) {
        allUrl = `${location.origin}/ad?${adReturn.pay_result_land}`;
        if (uniEnv.miniprogram) {
          this.$uni.redirectTo({
            url: "/pages/ad/ad?" + adReturn.pay_result_land,
          });
          return;
        }
      }
      if (!is_payment) {
        // window.location.replace(allUrl);
      }
      if (isWechat) {
        const customerHight = document.body.scrollHight;
        let machData = {
          action: "onIframeReady",
          displayStyle: "SHOW_CUSTOM_PAGE",
          hight: customerHight,
        };
        let postData = JSON.stringify(machData);
        window.parent.postMessage(postData, "https://payapp.weixin.qq.com");
      }

      setTimeout(() => {
        if (!needForm) {
          this.getResult({ ...query, ...adReturn });
          return;
        }
        if (isWechat) {
          let machData = { action: "jumpOut", jumpOutUrl: allUrl };
          let postData = JSON.stringify(machData);
          if (window.parent != window) {
            window.parent.postMessage(postData, "https://payapp.weixin.qq.com");
          } else {
            window.location.replace(allUrl);
          }
          return;
        }
        // this.$router.push({
        // 	path: "/pay-success",
        // 	query
        // });
        window.location.replace(allUrl);
      }, 2000);
    },
    getResult(query) {
      const { path } = this.$route;
      if (query.o_path !== path) {
        this.$router.replace({
          path,
          query: {
            ...query,
            o_path: path,
          },
        });
        // this.getResult(query);
        // return;
      }
      this.changeClickId(query);
      const { tg_id, tg_type, is_payment, form_type, status } = query;
      this.is_payment = is_payment != 0;
      this.form_type = (form_type || 0) * 1;
      console.log("getResult", query, this.is_payment);
      if (this.is_payment) {
        this.getInfo();
      }
      this.getTplInfo(tg_id, tg_type).then(() => {
        console.log("SUCCESS", status);
        if (status != "TRADE_SUCCESS") return;
        let isSome = this.behaviorList.some((v) => v.behavior_order);
        if (isSome) {
          this.behavior("order");
          return;
        }
        this.$nextTick(() => {
          includeJs.exec(
            `gdt('track', 'COMPLETE_ORDER', {'key1': 'value1', 'key2': 'value2'});`
          );
        });
      });
      this.getCus(tg_id, tg_type);
    },
    visibilitychange() {
      if (document.visibilityState == "visible") {
        // document.title = "页面可见";
        console.log("页面可见");
        if (this.is_payment) {
          this.getInfo();
        }
        //do something
      }
      if (document.visibilityState == "hidden") {
        // document.title = "页面不可见";
        console.log("页面不可见");
        //do something else
      }
    },
    async getInfo() {
      console.log("getInfo", merOrderId);
      const { merOrderId } = this.$route.query;
      if (!merOrderId) return;
      const data = await this.$api.getDepositData({
        merOrderId: merOrderId.substring(4),
      });
      if (data.status != 1) {
        // setTimeout(() => {
        //   this.getInfo();
        // }, 2000);
      }
      this.info = data;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "~@/assets/css/pay.scss";
</style>
